package test.utils;

import test.entity.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @Projectname: algorithm-training-camp
 * @Filename: TreeNodeUtil
 * @Author: FANSEA
 * @Date:2024/9/13 16:52
 */
public class TreeNodeUtil {
    public static TreeNode ROOT = TreeNodeUtil.createSimpleBinaryTree();

    public static TreeNode createSimpleBinaryTree() {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.right.left = new TreeNode(0);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        return root;
    }

    public static TreeNode arrayToTree(Integer[] arr) {
        if (arr == null || arr.length == 0) {
            return null;
        }

        TreeNode root = new TreeNode(arr[0]);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int i = 1;
        boolean end = false;
        while (!queue.isEmpty() && !end) {
            TreeNode node = queue.poll();

            // 左子节点
            if (i < arr.length) {
                if (arr[i] != null) {
                    node.left = new TreeNode(arr[i]);
                    queue.offer(node.left);
                } else {
                    node.left = null;
                }
                i++;
            } else {
                end = true;
            }

            // 右子节点
            if (!end && i < arr.length) {
                if (arr[i] != null) {
                    node.right = new TreeNode(arr[i]);
                    queue.offer(node.right);
                } else {
                    node.right = null;
                }
                i++;
            } else {
                end = true;
            }
        }
        return root;
    }





}
